#!/usr/bin/env python3
# -*- encoding: utf-8 -*-


import numpy as np


# 通过数值微分计算梯度
def numerical_gradient(f, x):
    h = 1e-4
    grad = np.zeros_like(x)

    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        idx = it.multi_index
        tmp_val = x[idx]

        x[idx] = float(tmp_val) + h
        fxh1 = f(x)     # f(x+h)

        x[idx] = float(tmp_val) - h
        fxh2 = f(x)     # f(x-h)

        grad[idx] = (fxh1 - fxh2) / (2 * h)
        x[idx] = tmp_val

        it.iternext()

    return grad
